package com.scalar.chiptrack.sales.actions;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.util.ArrayList;
import java.util.HashMap;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForward;

import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.utils.ConfigManager;
import com.scalar.chiptrack.sales.forms.SelectCustomerForm;
import com.scalar.chiptrack.sales.forms.SalesOrderForm;
import com.scalar.chiptrack.sales.LineItem;
import com.scalar.chiptrack.sales.SalesOrder;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.ScalarException;
import com.scalar.chiptrack.users.User;
import com.scalar.chiptrack.users.Functionality;
import com.scalar.chiptrack.sales.dao.*;
import com.scalar.chiptrack.commons.Address;
import com.scalar.chiptrack.commons.Constants;
import com.scalar.chiptrack.sales.*;


/**
 * Implementation of <strong>Action</strong> that gives customers list,
 * search with customer name, create sales order
 *
 * @author Kesava Kumar Achanala
 * @version $Revision: 1.14 $ $Date: 2011/01/24 08:21:32 $
 */

public final class SelectCustomerAction extends ChipTrackAction
{

    private static final String ACTION_NAME = "/selectCustomer.do";



    public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response ) throws Exception
    {
        String customerName     = null;
        ArrayList customersList = null;

        SelectCustomerForm subform  = (SelectCustomerForm) form;
        HashMap errors              = new HashMap();
        HttpSession session         = request.getSession();
        String action               = request.getParameter("action");
        String showModify           = "FALSE";
        int isSample                = 1; //default set to salesOrder
        if ( ( request.getParameter("isSample") != null ) && ( request.getParameter("isSample").length() > 0 ) )
        {
            isSample = Integer.parseInt( request.getParameter("isSample") );
        }
        User user = (User) session.getAttribute(SessionKeys.USER_KEY);
        if ( user == null )
        {
            session.setAttribute(SessionKeys.SOURCE_PAGE_KEY, ACTION_NAME + "?" + "isSample=" + request.getParameter("isSample"));
            return (mapping.findForward("login"));
        }

        if ( user.isActionAllowed( Functionality.CUSTOMER_DETAILS, User.USER_ACTION_VIEW ) )
        {
            showModify = "TRUE";
        }
        request.setAttribute( "showNewCustomerLink", showModify);

        if ( action == null )
        {
            action = "SelectCustomer";
        }

        if ( "SelectCustomer".equals( action ) )
        {
            request.setAttribute("customers", NewCustomerDAO.getAllCustomerNamesByUserTypeBySetup( null, user, null, isSample ));
            request.setAttribute("showList", "FALSE");

            return ( mapping.findForward( "customerList" ) );
        }
        if ( "DisplayCustomerSearch".equals( action ) )
        {
            subform.setCustomerName("");
            subform.setSelectedCustomer("0");
            request.setAttribute("customers", NewCustomerDAO.getAllCustomerNamesByUserTypeBySetup( null, user, null, isSample));
            request.setAttribute("showList", "FALSE");
            return (mapping.findForward("customerList"));
        }

        if ("SearchCustomer".equals(action))
        {
            customerName = BeanUtils.getSimpleProperty(form, "customerName");
            String selectedCustomer = BeanUtils.getSimpleProperty(form, "selectedCustomer");
            if ( Integer.parseInt(selectedCustomer) == 0 )
            {
                customersList = CustomerDAO.getAllCustomers(customerName.replaceAll("_", "[_]").replaceAll("%", "[%]"), user, isSample);
                request.setAttribute("customersList", customersList);
                request.setAttribute("customers", NewCustomerDAO.getAllCustomerNamesByUserTypeBySetup( null, user, null, isSample));

                if ( customersList.size() == 0 )
                {
                    errors.put( ERROR_CUSTOMER_NOT_FOUND, null );
                }
                else
                {
                    request.setAttribute( "showList", "TRUE" );
                }

                if (!errors.isEmpty())
                    request.setAttribute(SessionKeys.ERROR_MESSAGES, errors);
                return (mapping.findForward("customerList"));
            }
            else
            {

                SalesOrderForm salesform = new SalesOrderForm();
                SalesOrder salesOrder = SalesOrderDAO.getSalesOrderCustomerDetails( selectedCustomer );
                HashMap salesOrderMap = (HashMap) session.getAttribute("salesOrderMap");
                if (salesOrderMap == null) {
                    salesOrderMap = new HashMap();
                }
                salesOrderMap.put(selectedCustomer, salesOrder);
                session.setAttribute("salesOrderMap", salesOrderMap);

                PropertyUtils.copyProperties( salesform, salesOrder);

                //salesform.setSalesOrderNo(SalesOrderDAO.loadAutomatedSalesOrderNo());
				if( isSample == 1)
				{
					salesform.setSalesOrderNo ( SalesOrderDAO.loadAutomatedSalesOrderNo () );
                    if ( "0".equals ( salesform.getIsConsignmentSales() ) )
                    {
                        salesform.setSalesOrderNo( Constants.CONSIGNMENT_SALESORDER_NO_PREFIX  + "-" + salesform.getSalesOrderNo() ); //For Consignment adding prefix "C-"
                    }
                }
				else
				{
					salesform.setSalesOrderNo ( SalesOrderDAO.loadAutomatedSampleSalesOrderNo () );
				}

                if (salesform.getShippingMethodName() != null) {
                    salesform.setShippingMethodName(salesform.getShippingMethodName().trim());
                }
                if (salesform.getShippingAccount() != null) {
                    salesform.setShippingAccount(salesform.getShippingAccount().trim());
                }

                request.setAttribute("Account", salesform.getShippingMethodName() + "   #   " + salesform.getShippingAccount());
                request.setAttribute("Method", salesform.getShippingMethodName() + "   #   " + salesform.getShippingAccount());

                salesform.setBillingAddress(salesOrder.getBillingAddressAsObject().getAddressAsString());
                salesform.setShippingAddress(salesOrder.getShippingAddressAsObject().getAddressAsString());

                //set the marketing part# & mfg part#
                session.setAttribute("mktgParts", SalesOrderDAO.loadAllMarketingPartNumbers());

                salesOrder.setMfgParts(SalesOrderDAO.loadAllManfacturingPartNosOfCustomerWithOutobsolete(Integer.parseInt(selectedCustomer), isSample));
                //salesOrder.setMfgPartsWithComments(SalesOrderDAO.loadAllManfacturingPartNumbersWithComments(Integer.parseInt(selectedCustomer), isSample));
                if ( ConfigManager.getBooleanProperty(ConfigManager.PROP_SHOW_SALES_LINEITEM_BASE_ORDER_QTY) )
                {
                    salesOrder.setMfgPartsWithBaseOrderQty(SalesOrderDAO.loadManufacturingPartNumbersWithBaseOrderQty(null, Integer.parseInt(selectedCustomer)));
                }
                salesOrder.setMfgPartsWithCustomerPartNos(NewSalesOrderDAO.loadManfacturingPartNumbersWithCustomerPartNumbers(Integer.parseInt(selectedCustomer), salesform.getOdmId(), isSample ));
                //salesOrder.setMfgPartsWithLabelNumbers(NewSalesOrderDAO.loadManfacturingPartNumbersWithOdmLabelNumbers(Integer.parseInt(selectedCustomer), salesform.getOdmId(), isSample ));

                session.setAttribute("salesTaxes", SalesDAO.loadSalesTaxList());

                ArrayList contactpersons = CustomerDAO.getAllContactPersonsForCustomer(salesform.getCustomerId());
                contactpersons.add(salesOrder.getCustomerName());

                Address addressObject = CustomerDAO.getAddress(salesOrder.getBillingAddressId());
                ContactPerson contactPerson = new ContactPerson();
                contactPerson.setContactPerson(salesform.getCustomerName());
                contactPerson.setPhoneNumber(addressObject.getPhoneNumber());
                contactPerson.setCellNumber("");
                contactPerson.setFaxNumber(addressObject.getFaxNumber());
                contactPerson.setEmail(addressObject.getEmail());
                HashMap customerContactPersonMap = CustomerDAO.getContactPersonDetailsMap(Integer.parseInt(selectedCustomer));
                customerContactPersonMap.put(salesform.getCustomerName(), contactPerson);
                salesOrder.setCustomerContactPersonMap(customerContactPersonMap);

                HashMap billingAddressMap = CustomerDAO.getAddressDetailsMap(salesOrder.getBillingAddressId(), salesOrder.getBillingAddressAsObject());

                addressObject.setContactPerson("");
                addressObject.setCellNumber("");
                billingAddressMap.put("", addressObject.getAddressAsString());
                salesOrder.setBillingAddressMap(billingAddressMap);

                HashMap shippingAddressMap = CustomerDAO.getAddressDetailsMap(salesOrder.getShippingAddressId(), salesOrder.getShippingAddressAsObject());
                Address shipAddress = CustomerDAO.getAddress(salesOrder.getShippingAddressId());
                shippingAddressMap.put("", shipAddress.getAddressWithoutContactPersonAsString());
                salesOrder.setShippingAddressMap(shippingAddressMap);

                session.setAttribute("allShippingTerms", SalesDAO.getAllShippingTerms());
                session.setAttribute("allDeliveryTerms", SalesDAO.getAllDeliveryTerms(null));
                session.setAttribute("shippingInstructions", NewSalesOrderDAO.loadShippingInstructions(null));
                session.setAttribute("freightInstructions", NewSalesOrderDAO.loadFreightInstructions(null));

                request.setAttribute("salesOrderForm", salesform);

                ArrayList lineItems = SalesOrderAction.getLineItems(session, isSample);//getLineItems(session);

                request.setAttribute("lineItems", lineItems);
                request.setAttribute("lineItemsWithSubtotals", SalesOrderAction.loadLineItemsWithSubTotals(lineItems));
                request.setAttribute("customerId", selectedCustomer);

                salesform.setContactPerson(salesOrder.getContactPerson());
                salesOrder.setSalesPersons(CustomerDAO.loadAllSalesPersonsforCustomer(salesform.getCustomerId()));
                salesOrder.setSalesReps(CustomerDAO.loadAllSalesRepsforCustomer(salesform.getCustomerId()));
                salesOrder.setOdmList(CustomerRelationshipDAO.getAllOdmsForCustomer(selectedCustomer));
                salesOrder.setEndCustomerList( CustomerRelationshipDAO.getAllEndCustomersForCustomer( selectedCustomer ) ) ;
                saveToken(request);
                return (mapping.findForward("salesOrder"));
            }

        }
        return (mapping.findForward("customerList"));
    }

    private static ArrayList getLineItems(HttpSession session) throws ScalarException
    {
        ArrayList lineItems = new ArrayList();

        for (int i = 1; i < 6; i++)
        {
            LineItem lineItem = new LineItem();
            lineItem.setLineItemNo(i);
            lineItem.setPoLineItemNo(i);
            lineItems.add(lineItem);
        }
        session.setAttribute("maxLineItemNo", "6");
        return lineItems;
    }


}
